/**
 * MIT License
 * 
 * Copyright (c) 2017 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.tunnel.common.tunnel;

import com.tunnel.common.constant.Constant;
import com.tunnel.common.tcp.TcpBaseHandler;
import com.tunnel.common.util.ByteArrayUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * Tunnel的基础handler
 */
public abstract class TunnelBaseHandler extends TcpBaseHandler {
	
    public TunnelBaseHandler(String name) {
    	super(name);
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	super.channelActive(ctx);
    	//保存到消息队列，供消息队列心跳使用
    	TunnelDataQueueManager.addBeatHeartCtx(ctx);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	super.channelInactive(ctx);
    	//移出心跳消息队列
    	TunnelDataQueueManager.removeBeatHeartCtx(ctx);
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    	if(byteBuf.isReadable()){
    		byte flag = byteBuf.getByte(byteBuf.readerIndex());
    		//要求数据包都要留存第一位为标志位
    		byteBuf.skipBytes(1);
    		
    		//对收到的数据，做结尾符转换符的替换
    		byte[] data = new byte[byteBuf.readableBytes()];
    		byteBuf.getBytes(byteBuf.readerIndex(), data,0,data.length);
    		
    		if(data.length>Constant.TUNNEL_DATA_END_FLAG_CONVERT_BYTES.length){
    			data = ByteArrayUtil.replace(data, Constant.TUNNEL_DATA_END_FLAG_CONVERT_BYTES, Constant.TUNNEL_DATA_END_FLAG_BYTES);
    		}
    		
    		handleData(ctx, data, flag);
    	}
    }

    protected abstract void handleData(ChannelHandlerContext ctx, byte[] data, byte flag);
}